<template>
  <div ref="indexPageRef" class="index-page">
    <div class="search-container">
      <input 
        type="text" 
        v-model="searchQuery" 
        @input="debounceSearch"
        placeholder="搜索商品..."
        class="search-input"
      >
      <button @click="performSearch" class="search-button">搜索</button>
    </div>
    <div v-if="searchResults.length > 0" class="search-results">
      <h2>搜索结果</h2>
      <ul>
        <li v-for="product in searchResults" :key="product.id">
          <router-link :to="'/product/' + product.id">
            {{ product.name }} - ¥{{ product.price }}
          </router-link>
        </li>
      </ul>
    </div>
    <div v-else-if="hasSearched" class="no-results">
      没有找到匹配的商品,请尝试其他关键词。
    </div>
    <div class="banner-container">
      <swiper
        :modules="modules"
        :autoplay="{ delay: 5000, disableOnInteraction: false }"
        :pagination="{ clickable: true }"
        :navigation="true"
        :loop="true"
        class="banner-swiper"
      >
        <swiper-slide v-for="(slide, index) in bannerSlides" :key="index">
          <div class="banner-slide" :style="{ backgroundImage: `url(${slide.image})` }">
            <div class="banner-content">
              <h1>{{ slide.title }}</h1>
              <p>{{ slide.description }}</p>
              <button class="banner-cta">立即查看</button>
            </div>
          </div>
        </swiper-slide>
      </swiper>
    </div>
    <div ref="productListRef" class="content-wrapper">
      <section class="featured-products">
        <h2>热门推荐</h2>
        <div class="product-grid">
          <div v-for="product in featuredProducts" :key="product.id" class="product-card">
            <router-link :to="{ name: 'ProductDetail', params: { id: product.id } }">
              <img :src="product.image" :alt="product.name" />
            </router-link>
            <h3>{{ product.name }}</h3>
            <p class="price">¥{{ product.price.toFixed(2) }}</p>
            <div class="product-actions">
              <button 
                @click="addToCart(product, $event)" 
                class="add-to-cart-btn"
                :class="{ 'disabled': !userStore.isLoggedIn }"
                :title="!userStore.isLoggedIn ? '请先登录' : '加入购物车'"
              >
                加入购物车
              </button>
              <button 
                @click="buyNow(product)" 
                class="buy-now-btn"
                :class="{ 'disabled': !userStore.isLoggedIn }"
                :title="!userStore.isLoggedIn ? '请先登录' : '立即购买'"
              >
                立即购买
              </button>
            </div>
          </div>
        </div>
      </section>
      <section class="promo-banner">
        <router-link to="/special-offers" class="promo-link">
          <div class="promo-image"></div>
          <div class="promo-content">
            <h2>限时特惠</h2>
            <p>全场零食8折起,快来抢购！</p>
            <button>立即查看</button>
          </div>
        </router-link>
      </section>
      <section class="more-products">
        <h2>
          <router-link to="/all-products">更多商品</router-link>
        </h2>
        <div class="product-grid">
          <div v-for="product in moreProducts" :key="product.id" class="product-card">
            <router-link :to="{ name: 'ProductDetail', params: { id: product.id } }">
              <img :src="product.image" :alt="product.name" />
            </router-link>
            <h3>{{ product.name }}</h3>
            <p class="price">¥{{ product.price.toFixed(2) }}</p>
            <div class="product-actions">
              <button 
                @click="addToCart(product, $event)" 
                class="add-to-cart-btn"
                :class="{ 'disabled': !userStore.isLoggedIn }"
                :title="!userStore.isLoggedIn ? '请先登录' : '加入购物车'"
              >
                加入购物车
              </button>
              <button 
                @click="buyNow(product)" 
                class="buy-now-btn"
                :class="{ 'disabled': !userStore.isLoggedIn }"
                :title="!userStore.isLoggedIn ? '请先登录' : '立即购买'"
              >
                立即购买
              </button>
            </div>
          </div>
        </div>
      </section>
      <div 
        class="back-to-top"
        @click="scrollToProducts"
        title="返回商品列表"
      >
        ⬆
      </div>
      <div class="fixed-cart" @click="goToCart">
        <span class="cart-icon">🛒</span>
        <span class="cart-count" v-if="cartItemCount > 0">{{ cartItemCount }}</span>
      </div>
    </div>
    <div v-if="flyingImage" class="flying-image" :style="flyingImageStyle">
      <img :src="flyingImage" alt="Flying product" />
    </div>
   
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Autoplay, Pagination, Navigation } from 'swiper/modules';
import { useProductStore } from '../stores/productStore';
import { useCartStore } from '../stores/cartStore';
import { useUserStore } from '../stores/userStore';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';
const modules = [Autoplay, Pagination, Navigation];
const productStore = useProductStore();
const cartStore = useCartStore();
const userStore = useUserStore();
const router = useRouter();
const bannerSlides = ref([
  {
    title: '欢迎来到零食天堂',
    description: '尽情选购您喜爱零食，享受美味时光',
    image: '/images/banner1.jpg',
  },
  {
    title: '限时特惠',
    description: '多款零食折扣中，快来抢购吧！',
    image: '/images/banner2.jpg',
  },
  {
    title: '新品上市',
    description: '探索最新上架的零食，品尝前所未有的美味',
    image: '/images/banner3.jpg',
  },
]);
const featuredProducts = ref([]);
const moreProducts = ref([]);
onMounted(async () => {
  featuredProducts.value = productStore.products.slice(0, 4);
  moreProducts.value = productStore.products.slice(4);
});
const flyingImage = ref(null);
const flyingImageStyle = ref({});
const addToCart = (product, event) => {
  if (!userStore.isLoggedIn) {
    alert('请先登录后再操作');
    router.push('/login');
    return;
  }
  cartStore.addToCart(product);
  animateToCart(product.image, event);
};
const animateToCart = (productImage, event) => {
  const buttonRect = event.target.getBoundingClientRect();
  const startLeft = buttonRect.left + buttonRect.width / 2;
  const startTop = buttonRect.top + buttonRect.height / 2;
  const cartIcon = document.querySelector('.fixed-cart');
  const cartRect = cartIcon.getBoundingClientRect();
  const endLeft = cartRect.left + cartRect.width / 2;
  const endTop = cartRect.top + cartRect.height / 2;
  flyingImageStyle.value = {
    left: `${startLeft}px`,
    top: `${startTop}px`,
    opacity: 1,
    transform: 'scale(1)',
    transition: 'all 0.5s ease-in-out',
  };
  flyingImage.value = productImage;
  setTimeout(() => {
    flyingImageStyle.value = {
      ...flyingImageStyle.value,
      top: `${startTop - 100}px`,
    };
  }, 50);
  setTimeout(() => {
    flyingImageStyle.value = {
      ...flyingImageStyle.value,
      left: `${endLeft}px`,
      top: `${endTop}px`,
      opacity: 0,
      transform: 'scale(0.1)',
    };
  }, 550);
  setTimeout(() => {
    flyingImage.value = null;
  }, 1050);
};
const buyNow = (product) => {
  if (!userStore.isLoggedIn) {
    alert('请先登录后再操作');
    router.push('/login');
    return;
  }
  cartStore.clearCart();
  cartStore.addToCart(product);
  router.push('/Order/payment');
};
const cartItemCount = computed(() => cartStore.totalItems);
const goToCart = () => {
  if (!userStore.isLoggedIn) {
    alert('请先登录后再操作');
    router.push('/login');
    return;
  }
  router.push('/Cart/Cart');
};
const searchQuery = ref('');
const searchResults = ref([]);
const hasSearched = ref(false);
// 模拟的商品数据，实际应用中这些数据应该从API获取
const products = [
  { id: 1, name: '巧克力饼干', price: 9.9 },
  { id: 2, name: '薯片', price: 6.5 },
  { id: 3, name: '果冻', price: 4.5 },
  { id: 4, name: '牛奶糖', price: 12.0 },
  { id: 5, name: '巧克力', price: 15.0 },
];
const performSearch = () => {
  const query = searchQuery.value.toLowerCase();
  searchResults.value = products.filter(product => 
    product.name.toLowerCase().includes(query)
  );
  hasSearched.value = true;
};
let debounceTimeout;
const debounceSearch = () => {
  clearTimeout(debounceTimeout);
  debounceTimeout = setTimeout(performSearch, 3000);
};
const productListRef = ref(null);
const indexPageRef = ref(null);
const scrollToProducts = () => {
  if (indexPageRef.value) {
    indexPageRef.value.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    });
  }
};
</script>
<style scoped>
.banner-container {
  width: 100%;
  height: 50vh;
  margin-bottom: 4rem;
  max-width: 100%;
  overflow: hidden;
}
.banner-swiper {
  height: 100%;
}
.banner-slide {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  color: white;
  text-align: left;
  position: relative;
}
.banner-slide::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%);
}
.banner-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  position: relative;
  z-index: 1;
}
.banner-slide h1 {
  font-size: 3.5rem;
  margin-bottom: 1rem;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  animation: fadeInUp 0.5s ease-out;
}
.banner-slide p {
  font-size: 1.5rem;
  max-width: 600px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  margin-bottom: 2rem;
  animation: fadeInUp 0.5s ease-out 0.2s;
  animation-fill-mode: both;
}
.banner-cta {
  background-color: #f3c223;
  color: #333;
  border: none;
  padding: 0.8rem 2rem;
  font-size: 1.2rem;
  border-radius: 30px;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.3s;
  animation: fadeInUp 0.5s ease-out 0.4s;
  animation-fill-mode: both;
}
.banner-cta:hover {
  background-color: #f0b400;
  transform: translateY(-3px);
}
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
/* 自定义 Swiper 导航按钮样式 */
:global(.swiper-button-next),
:global(.swiper-button-prev) {
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  transition: background-color 0.3s;
}
:global(.swiper-button-next:hover),
:global(.swiper-button-prev:hover) {
  background-color: rgba(0, 0, 0, 0.7);
}
:global(.swiper-pagination-bullet) {
  background-color: white;
  opacity: 0.7;
}
:global(.swiper-pagination-bullet-active) {
  background-color: #f3c223;
  opacity: 1;
}
.content-container {
  max-width: 1200px;
  margin: 1rem auto;
  padding: 0 1rem;
}
.featured-products,
.more-products {
  margin-bottom: 2rem;
}
h2 {
  font-size: 1.5rem;
  margin-bottom: 1rem;
}
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
}
.product-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 1rem;
  text-align: center;
}
.product-card img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s ease;
}
.product-card img:hover {
  transform: scale(1.05);
}
.price {
  font-weight: bold;
  color: #e44d26;
}
button {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
button:hover {
  background-color: #45a049;
}
.promo-banner {
  position: relative;
  margin-bottom: 2rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f3c223;
  padding: 2rem;
  border-radius: 8px;
}
.promo-link {
  display: flex;
  align-items: center;
  justify-content: space-between;
  text-decoration: none;
  color: inherit;
  width: 100%;
}
.promo-image {
  width: 40%;
  height: 150px;
  background-color: #fff;
  border-radius: 8px;
}
.promo-content {
  width: 55%;
  color: #333;
}
.promo-content h2 {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}
.promo-content p {
  margin-bottom: 1rem;
}
.promo-content button {
  background-color: #333;
  color: #fff;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.promo-content button:hover {
  background-color: #555;
}
.more-products {
  margin-top: 2rem;
}
.more-products h2 {
  font-size: 1.5rem;
  margin-bottom: 1rem;
}
.product-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 1rem;
}
.add-to-cart-btn, .buy-now-btn {
  flex: 1;
  padding: 0.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.add-to-cart-btn {
  background-color: #4caf50;
  color: white;
  margin-right: 0.5rem;
}
.buy-now-btn {
  background-color: #f44336;
  color: white;
  margin-left: 0.5rem;
}
.add-to-cart-btn:hover {
  background-color: #45a049;
}
.buy-now-btn:hover {
  background-color: #d32f2f;
}
.fixed-cart {
  position: fixed;
  bottom: 80px;
  right: 20px;
  background-color: #f3c223;
  color: white;
  padding: 10px;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  z-index: 1001;
}
.fixed-cart:hover {
  transform: scale(1.1);
}
.cart-icon {
  font-size: 24px;
}
.cart-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: red;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: bold;
}
.flying-image {
  position: fixed;
  z-index: 9999;
  pointer-events: none;
}
.flying-image img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}
@media (max-width: 768px) {
  .fixed-cart {
    bottom: 10px;
    right: 10px;
    width: 50px;
    height: 50px;
  }
  .cart-icon {
    font-size: 20px;
    display: none; /* 隐藏购物车图标 */
  }
}
.search-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}
.search-input {
  width: 70%;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}
.search-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}
.search-button:hover {
  background-color: #0056b3;
}
.search-results, .no-results {
  margin-top: 20px;
}
.search-results h2 {
  color: #333;
}
.search-results ul {
  list-style-type: none;
  padding: 0;
}
.search-results li {
  margin-bottom: 10px;
}
.search-results a {
  text-decoration: none;
  color: #007bff;
}
.search-results a:hover {
  text-decoration: underline;
}
.no-results {
  color: #666;
  text-align: center;
}
.back-to-top {
  position: fixed;
  bottom: 90px;
  right: 20px;
  width: 45px;
  height: 45px;
  background-color: #f3c223;
  color: #333;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 24px; 
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  z-index: 999;
}
.back-to-top:hover {
  transform: translateY(-3px);
  background-color: #ffd700;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
@media (max-width: 768px) {
  .back-to-top {
    bottom: 70px;
    right: 10px;
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
}
.content-wrapper {
  /* 确保没有固定高度和滚动设置 */
  /* height: 500px; */
  /* overflow-y: auto; */
}
.index-page {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}
.add-to-cart-btn.disabled,
.buy-now-btn.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.add-to-cart-btn.disabled:hover,
.buy-now-btn.disabled:hover {
  background-color: inherit;
  transform: none;
}
</style>
